/**
 * Created by zhoumingrui on 2017/1/24.
 */
const ValidateStyle = require('./validate-style');
const ChartCache = require('../lib/cache');
const DataSource = require('../data/data-source');

const StyleChart = require('./style-chart');

const validateStyle = new ValidateStyle();

class Style {
    constructor(sup) {
        this.options = Object.assign({}, {
            sources: [],
            charts: []
        }, sup.options.style);

        this.sup = sup;

        this.chartCache = new ChartCache();
    }

    /**
     * 这个需要以dataSource分组。
     * @param style
     */
    parseStyle(style) {
        if (!validateStyle.validate(style)) return;

        let _souces = {};
        this.options.sources.map((d, i) => {
            _souces[d.id] = new DataSource(d);
        });

        this.options.charts.map((d) => {
            let source = _souces[d.sourceId];
            let o = Object.assign({}, d, {source: source});

            this.chartCache[o.id] = {
                chart: StyleChart.create(o),
                source: source
            }
        });

        this.sup.fire('style.doneloading');
    }

    renderStyle(id) {
        if (!id) {
            for (let key in this.chartCache) {
                this._renderChart(key);
            }
        } else {
            this._renderChart(id);
        }
    }

    resize(){
        for (let key in this.chartCache) {
            this.chartCache[key].chart.resize();
        }
    }

    _renderChart(id) {
        this.chartCache[id].chart.render();
    }

    /**
     * 按id更新source
     * @param id
     */
    updateSource(id, data) {
        if (!id) return;

        for (let key in this.chartCache) {
            let cache = this.chartCache[key];
            if (cache.source.id === id) {
                cache.source.data = data;
                this._renderChart(cache.chart.id);
            }
        }

    }
}

module.exports = Style;
